//
//  HKHomePageViewController.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/8.
//

#import "HKHomePageViewController.h"
#import <Masonry/Masonry.h>
#import "HKTableAdapter.h"
#import "HKHeaderCellViewModel.h"
#import "HKHeaderCellTableViewCell.h"
#import "HKCommonDefine.h"
#import "HKUser.h"
#import "HKUserInfoViewController.h"
#import "HKProfileHeaderView.h"
#import "UIView+properties.h"
#import "HKProfileListCellModel.h"
#import "HTTPURL.h"
#import "HKRequestDefine.h"
#import "HKLoadingView.h"
#import "UIView+HKSafeArea.h"
#import <MJRefresh/UIScrollView+MJRefresh.h>
#import "HKMainPageModel.h"
#import "HKMainPageListCellModel.h"
#import "HKToastView.h"
#import "HKWebViewController.h"
#import <BlocksKit/BlocksKit.h>
#import "HKCommonDefine.h"
#import "HKMainPageListCellModel.h"
#import "HKAvVideoRecorder.h"
#import "THRecorderController.h"
#import "HKShareAvaudioManager.h"
#import "HKNoticeModel.h"
#import "AppDelegate.h"

@interface HKHomePageViewController () <THRecorderControllerDelegate>

@property (nonatomic, strong) HKTableAdapter *tableAdapter;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *headerImageView;

@property (nonatomic, assign) BOOL isFirst;

@property (nonatomic, strong) UIButton *recorderButton;
@property (nonatomic, strong) UIButton *playButton;
//@property (nonatomic, strong) HKAvVideoRecorder *recorder;

@property (nonatomic,strong)THRecorderController *recorderController;

@end

@implementation HKHomePageViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isFirst = YES;
    self.userDefinedNaviBar.hidden = YES;
    
//    NSString *mp3Name = @"star_show30sec";
//    NSString *audioFileURL = [[NSBundle mainBundle] pathForResource:mp3Name ofType:@"wav"];
//    [[HKShareAvaudioManager sharedInstance] playWithUrl:[NSURL URLWithString:audioFileURL]];
    
    [self.view addSubview:self.headerView];
    [self.headerView addSubview:self.headerImageView];
   
    [self.headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.headerView).offset(-38);
        make.size.mas_equalTo(CGSizeMake(129, 30));
        make.left.mas_equalTo(KSLeftMargin);
    }];
    
    [self.view addSubview:self.tableView];
    WS
    CGFloat top = self.headerView.height;
    CGFloat bottom = [HKKeyWindow ks_safeAreaInsets].bottom + 44;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        SS
        make.top.mas_equalTo(top);
        make.bottom.mas_equalTo(-bottom);
        make.width.mas_equalTo(self.view);
    }];
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        SS
        [self requestData];
        
    }];
    self.tableView.mj_header = header;
    
    [self.tableView.mj_header beginRefreshing];
    
    [self requestMessageData];
    
//    _recorderController = [[THRecorderController alloc] init];
//    //_recorderController.delegate = self;
//    self.recorderButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 50, 100, 50)];
//    [self.recorderButton setTitle:@"开始录音音" forState:UIControlStateNormal];
//    [self.recorderButton setTitle:@"停止音音" forState:UIControlStateSelected];
//    [self.recorderButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [self.view addSubview:self.recorderButton];
//    [self.recorderButton addTarget:self action:@selector(onTapR:) forControlEvents:UIControlEventTouchUpInside];
//    
//    self.playButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 150, 100, 50)];
//    [self.playButton setTitle:@"开始播放" forState:UIControlStateNormal];
//    [self.playButton setTitle:@"停止播放" forState:UIControlStateSelected];
//    [self.playButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [self.view addSubview:self.playButton];
//    [self.playButton addTarget:self action:@selector(onTapP:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)requestMessageData {
    NSString *url = HKNoticeUrl;
    [HTTPURL getjsonRequest:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *response = KSSAFE_CAST(responseObject, NSDictionary);
        NSDictionary *data = response[@"data"];
        if (data && [data isKindOfClass:NSArray.class]) {
            NSArray<HKNoticeModel *> *noticeModels = [HKNoticeModel mj_objectArrayWithKeyValuesArray:response[@"data"]];
            __block BOOL isReadMessage = YES;
            [noticeModels enumerateObjectsUsingBlock:^(HKNoticeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (!obj.isRead){
                    isReadMessage = NO;
                }
            }];
            if (!isReadMessage){
                [[AppDelegate appDelegate].mainTabBarViewController showMessageTabbarItemBadge];
            }else{
                [[AppDelegate appDelegate].mainTabBarViewController clearMessageTabbarItemBadge];
            }
         }
    } filure:^(NSURLSessionDataTask *task, NSError *error) {
 
    }];
}

- (void)interruptionBegan {
    
}

//- (void)onTapR:(UIButton *)sender {
//    if (!sender.selected) {
//        [_recorderController record];
//    } else {
//        [_recorderController stopWithCompletionHandler:^(BOOL, str) {
//            
//        }];
//    }
//    sender.selected = !sender.selected;
//}

- (void)onTapP:(UIButton *)sender {
    if (!sender.selected) {
        [_recorderController play];
       // [self.recorder playAv];
    } else {
        [_recorderController stopPlay];
        //[self.recorder stopAV];
    }
    sender.selected = !sender.selected;
}

//- (HKAvVideoRecorder *)recorder {
//    if (!_recorder) {
//        _recorder = [HKAvVideoRecorder new];
//        //WS
//        [_recorder setToHasFinishRecordBlock:^{
//            //SS
////            [self uploadRecordFile];
//        }];
//    }
//    return _recorder;
//}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled =NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [HKUITool setStatusBarBackgroundColor:[UIColor whiteColor]];
    if (!self.isFirst) {
        [self.tableAdapter.sectionModels bk_each:^(id obj) {
            HKListSectionModel *listSectionModel = KSSAFE_CAST(obj, HKListSectionModel);
            if (listSectionModel) {
                [listSectionModel.cellModels bk_each:^(id obj) {
                    HKMainPageListCellModel *cellModel = KSSAFE_CAST(obj, HKMainPageListCellModel);
                    [cellModel reloadWebViewController];
                
                }];
            }
        }];
    }
    self.isFirst = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled =YES;
    }
}

- (void)requestData {
    NSString *url = HKMainUrl;
    [HTTPURL getjsonRequest:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *response = KSSAFE_CAST(responseObject, NSDictionary);
        NSDictionary *data = response[@"data"];
        [self.tableView.mj_header endRefreshing];
        if (data) {
            HKMainPageModel *model = [HKMainPageModel mj_objectWithKeyValues:data];
            [self setupCellModelsWithContent:model];
        } else {
            [self setupCellModelsWithContent:nil];
            [[HKToastView sharedToastView] showToast:@"数据为空"];
        }
    } filure:^(NSURLSessionDataTask *task, NSError *error) {
        [[HKToastView sharedToastView] showToast:error.domain?:@"网络请求失败"];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)setupCellModelsWithContent:(HKMainPageModel *)mainPageModel {
    [self.tableAdapter clear];
    HKListSectionModel *sectionModel = [HKListSectionModel new];
    
    NSMutableArray<HKMainPageListCellModel *> *listModels = [NSMutableArray array];
    
    if (mainPageModel) {
        HKMainPageListCellModel *mainCellModel = [[HKMainPageListCellModel alloc] initWithContent:mainPageModel];

        mainCellModel.context.fromViewController = self;
        [listModels addObject:mainCellModel];
    }
   
    HKMainPageModel *localPagemodel = [HKMainPageModel new];
    localPagemodel.recordId = 0;
    localPagemodel.isFromLocal = YES;
    localPagemodel.type = @"问卷列表";
    localPagemodel.name = @"问卷模型；填写问卷";
    HKMainPageListCellModel *sectionCellModel = [[HKMainPageListCellModel alloc] initWithContent:localPagemodel];

    sectionCellModel.context.fromViewController = self;
    [listModels addObject:sectionCellModel];
    
    [sectionModel addCellModels:listModels.copy];
    [self.tableAdapter addSectionModel:sectionModel];
    [self.tableAdapter reloadData];
}
#pragma mark - getter and setter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [HKTableAdapter createTableViewWithFrame:self.view.bounds];
        _tableView.backgroundColor = UIColorFromRGB(0xf7f7f7);
    }
    return _tableView;
}

- (HKTableAdapter *)tableAdapter {
    if (!_tableAdapter) {
        _tableAdapter = [[HKTableAdapter alloc] initWithTableView:self.tableView];
    }
    return _tableAdapter;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [UIView new];
        _headerView.frame = CGRectMake(0, 0, self.view.width, 134);
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}

- (UIImageView *)headerImageView {
    if (!_headerImageView) {
        _headerImageView = [UIImageView new];
        _headerImageView.image = [UIImage imageNamed:@"topImageView"];
    }
    return _headerImageView;
}

@end
